package com.example.chatclient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class ReceiveService {
	
	protected Socket socket;
	protected InputStream mmInStream;
	protected OutputStream mmOutStream;

	public ReceiveService() {}

	public ReceiveService(String ip, int port) throws IOException {
		socket = new Socket(ip, port);
		mmInStream = socket.getInputStream();
		mmOutStream = socket.getOutputStream();
	}

	public void receive(Handler handler) {
		byte[] buffer = new byte[1024];
		try {
			while (socket != null && socket.isConnected()) {
				int bytes = mmInStream.read(buffer);
				
				Log.d("TEST", String.valueOf(bytes));
				
				if (bytes <= 0)
					continue;
				String textReceive = "";
				textReceive = new String(buffer, 0, bytes, "UTF-8");
				Message msg = new Message();
				msg.obj = textReceive;
				handler.sendMessage(msg);
				
				Log.d("TEST", textReceive);
			}
		} catch (Exception e) {
		}
	}

	public Socket getSocket() {
		return socket;
	}	
}
